package com.yanyilu.basing.controller;


import com.yanyilu.basing.common.R;
import com.yanyilu.basing.entity.OrderForm;
import com.yanyilu.basing.jwt.JwtIgnore;
import com.yanyilu.basing.service.IOrderFormService;
import com.yanyilu.basing.util.ParseJwtUtil;
import com.yanyilu.basing.util.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Sxx
 * @since 2020-10-27
 */
@CrossOrigin
@RestController
@RequestMapping("/orderform")
public class OrderFormController {

    @Value("${uploadDir}")
    private String uploadDir;

    @Autowired
    IOrderFormService orderFormService;

    /**
     *
     * @param file
     * @return
     */
    @JwtIgnore
    @RequestMapping("/import")
    public HashMap<String, Object> upload(@RequestParam("file") MultipartFile file) {

        HashMap<String, Object> result = new HashMap<String, Object>();
        if (file.isEmpty()) {
            result.put("status", "文件上传失败");
            result.put("code", "500");
            result.put("msg", "文件大小为0");
            return result;
        } else {
            try {
                File dic = new File(uploadDir);
                if (dic.exists() && dic.isDirectory()) {
                    byte[] bytes = file.getBytes();
                    Path path = Paths.get(uploadDir + file.getOriginalFilename());
                    Files.write(path, bytes);

                    R r = new R();
                    r.ok(90001,"文件上传成功");


                    FileInputStream ins = new FileInputStream(new File(path.toString()));
                    System.out.println(ins);
                    XSSFWorkbook workbook = new XSSFWorkbook(ins);
                    Sheet sheet = workbook.getSheetAt(0);
                    System.out.println("报错了没4？");
                    int lastRowIndex = sheet.getLastRowNum();
                    System.out.println("共有" + lastRowIndex + "条记录");

                    for (int i = 0; i <= lastRowIndex; i++) {
                        Row row = sheet.getRow(i);
                        if (row == null) {
                            return R.ok(90002,"第"+(i+1)+"数据异常");
//                            break;
                        }

                        String phone = row.getCell(0).getStringCellValue().split("\\:")[1];
                        System.out.println("phone"+phone);
                        OrderForm order = orderFormService.orderByCon(phone);
                        if(null!=order){
                            order.setMailOrderNo(row.getCell(1).getStringCellValue());
                            order.setMailStatus(1);
                            orderFormService.adminUpdate(order);
                        }else {
                            System.out.println("111111");
                        }
                    }
                    System.out.println("报错了没1？");
                    File deleteFile = new File(path.toString());
                    deleteFile.delete();
                    return R.ok(90001,"文件上传成功");
                } else {
                    dic.mkdir();
                    byte[] bytes = file.getBytes();
                    Path path = Paths.get(uploadDir + file.getOriginalFilename());
                    Files.write(path, bytes);
                    return R.ok(90001,"文件上传成功");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return R.error(90003,"文件上传失败");
            }
        }
    }

    /**
     * 创建并展示支付信息
     * @return
     */
    @GetMapping("/frontend/order")
    public R getOrder(){
        Integer userId = ParseJwtUtil.getUserId();
        return orderFormService.getOrder(userId);
    }

    /**
     * 订单详情页展示
     * @return
     */
    @GetMapping("/frontend/info")
    public R getOrderInfo(){
        Integer userId = ParseJwtUtil.getUserId();
        return orderFormService.getOrderInfo(userId);
    }

    /**
     * 统一下单
     * @return
     */
    @GetMapping("/frontend/pay")
    public R unifiedorder(HttpServletRequest request){
        Integer userId = ParseJwtUtil.getUserId();
        return orderFormService.unifiedorder(userId,request);
    }

    /**
     * 修改订单
     * @param orderForm
     * @return
     */
    @PostMapping("/frontend/update")
    public R updateOrder(@RequestBody OrderForm orderForm){
        Integer userId = ParseJwtUtil.getUserId();
        return orderFormService.updateOrder(orderForm,userId);
    }

    /**
     * 确认收货
     * @param orderFormId
     * @return
     */
    @GetMapping("/frontend/check")
    public R check(@RequestParam("orderFormId")Integer orderFormId){

        return orderFormService.checkOrder(orderFormId);
    }
    /**
     * 支付成功回调地址
     */
    @JwtIgnore
    @RequestMapping(value = "/frontend/callback", produces = MediaType.APPLICATION_JSON_VALUE)
    // @RequestDescription("支付回调地址")
    @ResponseBody
    public String notifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
        orderFormService.callBack(request);
        Map<String, String> return_data = new HashMap<>();
        return_data.put("return_code", "SUCCESS");
        return_data.put("return_msg", "OK");
        return StringUtils.GetMapToXML(return_data);
    }

    /**
     * 后台订单列表
     * @param page
     * @param limit
     * @param orderNumber
     * @return
     */
    @RequestMapping("/admin/list")
    public R adminOrderFormList(@RequestParam("page")Integer page,@RequestParam("limit")Integer limit,
                                @RequestParam(value = "orderNumber",required = false)String orderNumber){
        return orderFormService.adminOrderFormList(page,limit,orderNumber);
    }

    /**
     * 删除订单
     * @param orderFormId
     * @return
     */
    @RequestMapping("/admin/delete")
    public R adminDelete(@RequestParam("orderFormId")Integer orderFormId){

        return orderFormService.adminDelete(orderFormId);
    }

    /**
     * 修改订单
     * @param orderForm
     * @return
     */
    //@JwtIgnore
    @RequestMapping("/admin/update")
    public R adminUpdate(@RequestBody OrderForm orderForm){
        return orderFormService.adminUpdate(orderForm);
    }
}
